﻿using AutoMapper;
using B.S.Backtrack.Domain.Entities;
using B.S.Backtrack.ErrorCode;
using B.S.Backtrack.Infrastructure.Interface;
using B.S.Backtrack.Write.API.Application.Command.Cultures;
using MediatR;

namespace B.S.Backtrack.Write.API.Application.CommandHandler.Cultures
{
    public class CreateCultureHandler : IRequestHandler<CreateCultureCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<Culture> culRep;
        private readonly IMapper mapper;

        public CreateCultureHandler(IBaseRepository<Culture> culRep,IMapper mapper)
        {
            this.culRep = culRep;
            this.mapper = mapper;
        }
        public Task<ApiResult<int>> Handle(CreateCultureCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            //获取现有的实体
            var entity = culRep.GetAll().Where(x=>x.ProductId==request.ProductId).FirstOrDefault();
            if (entity == null) 
            {
                var model = mapper.Map<Culture>(request);
                culRep.Add(model);
                result.Code = ApiEnums.添加成功;
                result.Msg = ApiEnums.添加成功.ToString();
                result.Data = 1;
            }
            else
            {
                mapper.Map(request,entity);
                culRep.Update(entity);
                result.Code = ApiEnums.修改成功;
                result.Msg = ApiEnums.修改成功.ToString();
                result.Data = 1;
            }
          
            return Task.FromResult(result);
        }
    }
}
